/**
 * @file tslib.c
 *
 */

/*********************
 *      INCLUDES
 *********************/
#include "libts.h"
#if USE_LIBTS != 0

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#include <include/tslib.h>
#ifdef DEBUG
#define dbg printk
#else
#define dbg(...)
#endif

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

/**********************
 *  STATIC VARIABLES
 **********************/
static struct tsdev *g_ts;
static struct ts_sample samp;

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

/**
 * Initialize the libts interface
 */
int libts_init(void)
{
	char * tsdev = getenv("TSLIB_TSDEVICE");
	int ret = 0;
	if (!tsdev)
		tsdev = LIBTS_NAME;

	g_ts = ts_open(tsdev, 0);
	if (g_ts)
		ts_config(g_ts);
	else
	{
		perror("open touch device error!\n");
		ret = -1;
	}
	
	return ret;
}

/**
 * Get the current position and state of the libts
 * @param data store the libts data here
 * @return false: because the points are not buffered, so no more data to be read
 */
bool tslib_read(lv_indev_drv_t * drv, lv_indev_data_t * data)
{
   if (ts_read(g_ts, &samp, 1) == 1) 
	{
		data->point.x = samp.x;
		data->point.y = samp.y; 
		dbg("%ld.%06ld: %6d %6d %6d\n", samp.tv.tv_sec, samp.tv.tv_usec, samp.x, samp.y, samp.pressure);
	}

	data->state = (samp.pressure == 0) ? LV_INDEV_STATE_REL : LV_INDEV_STATE_PR;      //抬起

	if (data->point.x < 0)
		data->point.x = 0;
	if (data->point.y < 0)
		data->point.y = 0;
	if (data->point.x >= lv_disp_get_hor_res(drv->disp))
		data->point.x = lv_disp_get_hor_res(drv->disp) - 1;
	if (data->point.y >= lv_disp_get_ver_res(drv->disp))
		data->point.y = lv_disp_get_ver_res(drv->disp) - 1;

	return false;
}

#endif
